// MainActivity.kt
package com.example.cardgame

import android.content.SharedPreferences
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.collection.mutableLongListOf
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.children
import androidx.gridlayout.widget.GridLayout
import cn.edu.sicnu.cardgame.CardMatchingGame

class MainActivity : AppCompatActivity(), View.OnClickListener {

    private lateinit var sharedPreferences: SharedPreferences
    lateinit var game: CardMatchingGame
    val cardButtons = mutableListOf<Button>()
    val gridLayout: GridLayout by lazy { findViewById(R.id.gridLayout) }
    val reset: Button by lazy { findViewById(R.id.reset) }
    val score: TextView by lazy { findViewById(R.id.score) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        sharedPreferences = getSharedPreferences("user_info", MODE_PRIVATE)

        for (v in gridLayout.children) {
            if (v is Button) {
                v.setOnClickListener(this)
                cardButtons.add(v)
            }
        }

        game = CardMatchingGame(cardButtons.count())
        updateUI()

        reset.setOnClickListener {
            saveHighScoreIfNeeded(game.score)
            game = CardMatchingGame(cardButtons.count())
            updateUI()
        }
    }

    fun updateUI() {
        for (button in cardButtons) {
            val index = cardButtons.indexOf(button)
            val card = game.cardAtIndex(index)
            button.isEnabled = !card.isMatched
            if (card.isChosen) {
                button.text = card.toString()
                button.setBackgroundColor(Color.WHITE)
            } else {
                button.text = ""
                button.setBackgroundResource(R.drawable.img)
            }
        }
        score.text = String.format("%s%d", "Score:", game.score)
    }

    private fun saveHighScoreIfNeeded(currentScore: Int) {
        val highScore = sharedPreferences.getInt("score", 0)
        if (currentScore > highScore) {
            with(sharedPreferences.edit()) {
                putInt("score", currentScore)
                apply()
            }
        }
    }

    override fun onClick(v: View?) {
        if (v is Button) {
            val index = cardButtons.indexOf(v)
            game.chooseCardAtIndex(index)
            updateUI()
        }
    }
}